#!/bin/bash

# Get the directory this script is in (inside the .app bundle)
DIR="$(cd "$(dirname "$0")" && pwd)"
RESOURCES="$DIR/../Resources"
INSTALLER_FILES="$RESOURCES/installer_files"

# Find Python 3
PYTHON=$(which python3 2>/dev/null)
if [ -z "$PYTHON" ]; then
    osascript -e 'display dialog "Python 3 is required but was not found on this Mac. Please install it from python.org." buttons {"OK"} default button "OK" with icon stop with title "Robot Food Agent"'
    exit 1
fi

# Create install directories
INSTALL_DIR="$HOME/Library/Application Support/co.uk.robotfood"
LAUNCH_AGENTS="$HOME/Library/LaunchAgents"
PLIST="$LAUNCH_AGENTS/co.uk.robotfood.agent.plist"
AGENT="$INSTALL_DIR/agent.py"

mkdir -p "$INSTALL_DIR/.rf"
mkdir -p "$LAUNCH_AGENTS"

# Copy files
cp "$INSTALLER_FILES/agent.py" "$AGENT"
cp "$INSTALLER_FILES/.rf/rfaa.rfx" "$INSTALL_DIR/.rf/rfaa.rfx"
cp "$INSTALLER_FILES/.rf/rfpack.rfx" "$INSTALL_DIR/.rf/rfpack.rfx"
chmod +x "$AGENT"

# Install websockets
"$PYTHON" -m pip install websockets --quiet 2>/dev/null || true

# Write launchd plist
cat > "$PLIST" << PLISTEOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>co.uk.robotfood.agent</string>
    <key>ProgramArguments</key>
    <array>
        <string>$PYTHON</string>
        <string>$AGENT</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>StandardErrorPath</key>
    <string>/tmp/rf_agent.log</string>
    <key>StandardOutPath</key>
    <string>/tmp/rf_agent.log</string>
</dict>
</plist>
PLISTEOF

# Load the agent
launchctl unload "$PLIST" 2>/dev/null || true
launchctl load "$PLIST"

# Success message
osascript -e 'display dialog "Robot Food Agent installed and running!" buttons {"Open Tool", "Done"} default button "Open Tool" with icon note with title "Robot Food Agent"
if button returned of result is "Open Tool" then
    do shell script "open '"'"'https://robotfood.co.uk/automation/'"'"'"
end if'
